package info.ferrarimarco.itEbooksDownloader.controller;

import info.ferrarimarco.java.helper.html.HtmlHelper;
import info.ferrarimarco.java.helper.http.HttpHelper;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

public class BookNameDownloader {
	
	public static List<String> downloadNames(int firstBookIndex, int lastBookIndex, String tagStart, String tagEnd) throws IOException {

		List<String> names = new ArrayList<String>(lastBookIndex - firstBookIndex + 1);
		
		for(int i = firstBookIndex; i <= lastBookIndex; i++){
			String url = "http://it-ebooks.info/book/" + i + "/";
			String name = i + ":";
			name = getBookName(url, i, tagStart, tagEnd);
			names.add(name);
		}
		
		System.out.println("Book names downloaded.");
		
		return names;
	}
	
	public static String getBookName(String url, int bookIndex, String tagStart, String tagEnd) {
		
		String pageSource = null;
		String name = bookIndex + ":";
		
		boolean found = false;
		int maxTries = 100;
		int tries = 0;
		
		while(!found && tries < maxTries){
			try {
				pageSource = HttpHelper.writeHtmltoString(url);
				name += HtmlHelper.getTagContents(pageSource, tagStart, tagEnd);
				found = true;
			} catch (SocketTimeoutException e) {
				tries++;
			}catch(MalformedURLException e){
				tries++;
			}catch (IOException e){
				tries++;
			}	
		}
		
		if(!found){
			name += "ERROR DOWNLOADING NAME";
		}

		System.out.println("Book name " + name);
		
		return name;
	}

}
